package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.session.MediaSession;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.utils.AESUtil;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import cn.jpush.android.api.JPushInterface;

public class UserUpActivity extends BaseActivity implements View.OnClickListener, AMapLocationListener {
    private TextView userupword;
    private Button userupregist;
    private TextView upregist;
    private ImageView userupback;
    private Button userupright;
    private String appid;
    private String rid;
    private String userId;
    private String token;
    private EditText userword;
    private EditText userupphone;
    private String word;
    private String phone;
    private String aWord;
    private SharedPreferences sharedPreferences;
    private TextView findword;
    private TelephonyManager telephonyManager;
    private double latitude1;
    private double longitude1;
    private String id;
    private String appid1;
    private String longitude;
    private String latitude;
    private double latitude2;
    private double longitude2;
    private String city;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_up);
        initUserupView();
        id = JPushInterface.getRegistrationID(this);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        rid = sharedPreferences.getString("rid", "");
        appid = sharedPreferences.getString("appid", "");
        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        if (rid==""&appid==""){
            fixingregst(id);
        }else {}
    }

    // 设备注册和验证
    private void fixingregst(final String id) {

        telephonyManager = (TelephonyManager) UserUpActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
        String line1Number = Build.VERSION.RELEASE;
        String pin =  Build.MODEL;
        String Imsi =  telephonyManager.getDeviceId();
        getLoc();
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/equipment/register");
        params.setHeader("Content-Type","application/json");
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("deviceId",Imsi);
        object.put("brand",pin);
        object.put("version",line1Number);
        object.put("registrationId",id);
        object.put("longitude",longitude);
        object.put("latitude",latitude);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取appid
                String data = obj.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                appid1 = obj1.getString("appId");
                SharedPreferences sharedPreferences = getSharedPreferences("userlogin",Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("rid",id);
                edit.putString("appid",appid1);
                edit.commit();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {


            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }
    // 获取位置信息 经纬度
    public void getLoc() {
        AMapLocationClient client = new AMapLocationClient(UserUpActivity.this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setInterval(300000);
        client.setLocationListener(this);
        client.setLocationOption(option);
        client.startLocation();

    }

    // 初始化控件
    private void initUserupView() {
        userupback = (ImageView) findViewById(R.id.userup_back);// 返回
        upregist = (TextView) findViewById(R.id.userup_regist);// 注册
        userupword = (TextView) findViewById(R.id.userup_inputword);// 密码
        userupright = (Button) findViewById(R.id.rightup);// 登陆
        findword = (TextView) findViewById(R.id.userup_word);

        userword = (EditText) findViewById(R.id.userup_inputword);
        userupphone = (EditText) findViewById(R.id.userup_inputphone);
        backmain = (ImageView) findViewById(R.id.userup_backmain);
        // 设置点击监听
        upregist.setOnClickListener(this);
        userupword.setOnClickListener(this);
        userupright.setOnClickListener(this);
        findword.setOnClickListener(this);
        userupback.setOnClickListener(this);
        backmain.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.userup_back:// 返回
                finish();
                break;
            case R.id.userup_regist:// 跳转到注册
                startActivity(new Intent(this,UserRegistActivity.class));
                finish();
                break;
            case R.id.userup_word:// 跳转到找回密码
                startActivity(new Intent(this,FindWordActivity.class));
                finish();
                break;
            case R.id.rightup://立即登陆
                if (rid==""&appid==""){
                    
                    UserLogin(appid1,id);
                }else {
                    
                    UserLogin(appid,id);
                }

                break;
        }
    }
    // 用户登陆
    public void UserLogin(String app,String id) {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/login");// 登陆接口
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId",app);
        getText();
        final JSONObject jsonObject = new JSONObject();
        jsonObject.put("username",phone);
        jsonObject.put("password",aWord);
        jsonObject.put("registrationId",id);
        jsonObject.put("longitude",longitude);
        jsonObject.put("latitude",latitude);
        Log.d("tag", "onSuccess: 登陆---"+app+"//"+phone+"//"+aWord+"//"+id+"//"+longitude+"//"+latitude);
        params.setBodyContent(jsonObject.toJSONString());
       x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 登陆---"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    String data = obj.getString("data");
                    com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                    userId = obj1.getString("userId");
                    token = obj1.getString("token");
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("userId",userId);
                    edit.putString("token", token);
                    edit.putString("phone", phone);
                    edit.putString("word", aWord);
                    edit.commit();
                    startActivity(new Intent(UserUpActivity.this,MainActivity.class));
                    UserUpActivity.this.finish();
                }else{
                    String failure = obj.getString("failure");
                    if (failure.equals("1002")){
                        Toast.makeText(UserUpActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1003")){
                        Toast.makeText(UserUpActivity.this, "账号被禁用", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1009")){
                        Toast.makeText(UserUpActivity.this, "手机号未注册", Toast.LENGTH_SHORT).show();
                    }else {}
                    
                }
              
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 登陆--"+ex);

                Toast.makeText(UserUpActivity.this, "登陆失败,密码或账号错误", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("tag", "onCancelled: cex--"+cex);
            }
            @Override
            public void onFinished() {

            }

        });
    }
    private void getText(){
        word = String.valueOf(userupword.getText());
        phone = String.valueOf(userupphone.getText());
        try {
            aWord = AESUtil.encryptAES(word);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        latitude2 = aMapLocation.getLatitude();
        longitude2 = aMapLocation.getLongitude();
        city = aMapLocation.getCity();
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString("latitude",String.valueOf(latitude));
        edit.putString("longitude",String.valueOf(longitude));
        edit.putString("city",city);
        edit.commit();

    }
}
